package main

import (
	"flag"
	"fmt"
	"io"
	"net/http"
	"os"
	"path/filepath"

	"github.com/xuri/excelize/v2"
)

func main() {
	// 定义命令行参数
	excelFilePath := flag.String("file", "your_excel_file.xlsx", "Excel文件路径")
	flag.Parse()

	// 读取Excel文件
	f, err := excelize.OpenFile(*excelFilePath)
	if err != nil {
		fmt.Println("打开Excel文件失败:", err)
		return
	}

	// 获取表格工作表名（假设只有一个sheet）
	sheetName := f.GetSheetName(0)

	// 获取【下载路径】列的索引
	downloadPathCol := getColIndex(f, sheetName, "下载路径")
	phoneCol := getColIndex(f, sheetName, "手机号")

	if downloadPathCol == -1 || phoneCol == -1 {
		fmt.Println("列名未找到")
		return
	}

	// 创建imgs文件夹
	imgsDir := "./imgs"
	if err := os.MkdirAll(imgsDir, os.ModePerm); err != nil {
		fmt.Println("创建文件夹失败:", err)
		return
	}

	// 遍历每一行数据
	rows, err := f.GetRows(sheetName)
	if err != nil {
		fmt.Println("读取行失败:", err)
		return
	}

	for _, row := range rows[1:] { // 跳过标题行
		downloadURL := row[downloadPathCol]
		phone := row[phoneCol]

		if downloadURL == "" || phone == "" {
			continue
		}

		// 下载图片
		resp, err := http.Get(downloadURL)
		if err != nil {
			fmt.Printf("下载图片失败: %s, 错误: %v\n", downloadURL, err)
			continue
		}
		defer resp.Body.Close()

		// 创建文件
		filePath := filepath.Join(imgsDir, phone+".jpg")
		out, err := os.Create(filePath)
		if err != nil {
			fmt.Printf("创建文件失败: %s, 错误: %v\n", filePath, err)
			continue
		}
		defer out.Close()

		// 保存图片
		_, err = io.Copy(out, resp.Body)
		if err != nil {
			fmt.Printf("保存图片失败: %s, 错误: %v\n", filePath, err)
			continue
		}

		fmt.Printf("图片已保存: %s\n", filePath)
	}
}

// 获取列索引
func getColIndex(f *excelize.File, sheetName, colName string) int {
	rows, err := f.GetRows(sheetName)
	if err != nil {
		fmt.Println("读取行失败:", err)
		return -1
	}

	for i, cell := range rows[0] {
		if cell == colName {
			return i
		}
	}
	return -1
}
